/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tad.cdi.mods.properties;

import com.tad.cdi.mods.properties.annotations.Bundle;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.inject.Inject;

/**
 *
 * @author johnament
 */
public class BundleProducer {

    @Inject
    BeanManager beanManager;

    @Produces
    public ResourceBundle produceResourceBundle(InjectionPoint ip) {
        Bundle b = null;
        if (ip.getAnnotated().isAnnotationPresent(Bundle.class)) {
            b = ip.getAnnotated().getAnnotation(Bundle.class);
        }
        Class container = ip.getMember().getDeclaringClass();
        String baseName = (b == null || b.baseName().equals("")) ? container.getCanonicalName() : b.baseName();
        Locale locale = null;
        try {
            Bean localeBean = (Bean) beanManager.getBeans(Locale.class).iterator().next();
            CreationalContext cc = beanManager.createCreationalContext(localeBean);
            Locale producedLocale = (Locale) beanManager.getReference(localeBean, Locale.class, cc);
            locale = producedLocale;
        } catch (Exception e) {
            //not sure what to do here yet.
            System.out.println("Caught an exception trying to load a ResourceBundle");
            if (b == null) {
                locale = Locale.getDefault();
            } else if (b.locale().equals("") || b.locale().equals("default")) {
                locale = Locale.getDefault();
            } else {
                String[] lpieces = b.locale().split("_", 3);
                switch (lpieces.length) {
                    case 0:
                        locale = Locale.getDefault();
                        break;
                    case 1:
                        locale = new Locale(lpieces[0]);
                        break;
                    case 2:
                        locale = new Locale(lpieces[0], lpieces[1]);
                        break;
                    case 3:
                        locale = new Locale(lpieces[0], lpieces[1], lpieces[2]);
                        break;
                    default:
                        locale = Locale.getDefault();
                        break;
                }
            }
        }
        baseName = baseName.replace(".", "/");
        return ResourceBundle.getBundle(baseName, locale);
    }
}
